﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LowLevelGraphics.Filter
{
    // TODO: resolve
    public sealed class ColorSpaceConverter
    {

        public void RGBToXYZ(double R, double G, double B, ref double X, ref double Y, ref double Z)
        {

            X = (R * 0.5140830 + G * 0.323889 + B * 0.1620280);
            Y = (R * 0.2650740 + G * 0.670115 + B * 0.0648112);
            Z = (R * 0.0240976 + G * 0.122854 + B * 0.8533480);
            /*
            R = ((R > 0.04045) ? Math.Pow((R + 0.055) / 1.055, 2.4) : (R / 12.92));
            G = ((G > 0.04045) ? Math.Pow((G + 0.055) / 1.055, 2.4) : (G / 12.92));
            B = ((B > 0.04045) ? Math.Pow((B + 0.055) / 1.055, 2.4) : (B / 12.92));

            X = (R * 0.4124 + G * 0.3576 + B * 0.1805);
            Y = (R * 0.2126 + G * 0.7152 + B * 0.0722);
            Z = (R * 0.0193 + G * 0.1192 + B * 0.9505);
            */
        }

        public void XYZToRGB(double X, double Y, double Z, ref double R, ref double G, ref double B)
        {

            R = (X * 2.565620 + Y * -1.166990 + Z * -0.398511);
            G = (X * -1.022090 + Y * 1.978260 + Z * 0.043821);
            B = (X * 0.074698 + Y * -0.251851 + Z * 1.176800);
            /*
            R = (X *  3.2406 + Y * -1.5372 + Z * -0.4986);
            G = (X * -0.9689 + Y *  1.8758 + Z *  0.0415);
            B = (X *  0.0557 + Y * -0.2040 + Z *  1.0570);

            R = ((R > 0.0031308) ? (1.055 * Math.Pow(R, 1 / 2.4) - 0.055) : (12.92 * R));
            G = ((G > 0.0031308) ? (1.055 * Math.Pow(G, 1 / 2.4) - 0.055) : (12.92 * G));
            B = ((B > 0.0031308) ? (1.055 * Math.Pow(B, 1 / 2.4) - 0.055) : (12.92 * B));
            */
        }

        public void XYZToYxy(double X, double Y, double Z, ref double Y_, ref double x_, ref double y_)
        {

            Y_ = Y;
            x_ = (X / (X + Y + Z));
            y_ = (Y / (X + Y + Z));
        }

        public void YxyToXYZ(double Y_, double x_, double y_, ref double X, ref double Y, ref double Z)
        {

            X = (x_ * (Y_ / y_));
            Y = Y_;
            Z = ((1 - x_ - y_) * (Y_ / y_));
        }
    }
}
